import { PaginatorPlugin } from "@datorama/akita";
import { switchMap, tap } from "rxjs/operators";

import { MessagesQuery, MessagesStore, makeStore, MessageEntity } from "@/state/messageEntity/store";
import { makeStore as makeMsgStore, MessageQuery } from '@/state/message/store'
import messageService from "@/services/messageService";

export class TwMessagesFacade {
  constructor(private store: MessagesStore, private query: MessagesQuery, private msgQuery: MessageQuery, public paginator: PaginatorPlugin<MessageEntity>) {
    //this.getWatchedRoom = this.getWatchedRoom.bind(this);
  }

  readonly filter$ = this.query.filter$;

  pagination$ = this.paginator.pageChanges.pipe(
    switchMap((pageNum) => {
      const reqFn = () => messageService.getPendingMsgsSvc(this.msgQuery.groupId, pageNum, 10);
      return this.paginator.getPage(reqFn);
    })
  )

  //批量放行消息，包括单条
  passPendingMsg = (ids: string[]) => {
    return messageService.passPendingMsgsSvc(this.msgQuery.groupId, ids)
      .pipe(
        tap(() => {
          //FIXME 移除本地已处理的记录，如果只能移除一条还需要修改
          this.store.remove(({ id }) => ids.indexOf(id) > -1)
        })
      )
  }

  prevPage = () => {
    this.paginator.prevPage();
  }

  nextPage = () => {
    this.paginator.nextPage();
  }

  refreshPage = () => {
    this.paginator.refreshCurrentPage();
  }

  //销毁store实例，释放内存
  destroy = () => {
    this.paginator.destroy();
    this.store.destroy();
  }
}

export const makeFacade = (): TwMessagesFacade => {
  const [store, query, paginator] = makeStore();
  const [, msgQuery] = makeMsgStore();

  return new TwMessagesFacade(store, query, msgQuery, paginator);
}